package com.nexgo.payment.action.online;

import android.content.Context;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.text.TextUtils;
import android.view.Gravity;

import com.nexgo.payment.R;
import com.nexgo.payment.action.Action;
import com.nexgo.payment.action.ActionResult;
import com.nexgo.payment.action.ActionStep;
import com.nexgo.payment.action.OnActionListener;
import com.nexgo.payment.constrant.SysConstant;
import com.nexgo.payment.databases.Repository;
import com.nexgo.payment.entity.MessageData;
import com.nexgo.payment.entity.TransData;
import com.nexgo.payment.fragment.ProgressDialogFragment;
import com.nexgo.payment.fragment.TextDialogFragment;
import com.nexgo.payment.util.StringUtils;
import com.nexgo.sound.SoundManager;

/**
 * Created by xiaox on 2017/7/10.
 */

public class OnlineDialogFragment extends ProgressDialogFragment implements Action<ActionStep>, OnlineContract.View {

    public static final String TRANS_DATA = "trans_data";
    public static final String TIP = "tip";

    private OnActionListener mListener;
    private OnlineContract.Presenter mPresenter;
    private MyDownTimer mDownTimer;
    private int mCountTime = 0;

    public static OnlineDialogFragment newInstance(TransData transData, String tip) {
        OnlineDialogFragment onlineDialogFragment = new OnlineDialogFragment();
        Bundle b = new Bundle();
        b.putParcelable(TRANS_DATA, transData);
        b.putString(TIP, tip);
        onlineDialogFragment.setArguments(b);
        return onlineDialogFragment;
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        if (context instanceof OnActionListener) {
            mListener = (OnActionListener) context;
        }
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        showTip(getString(R.string.pls_wait));
        TransData transData = null;
        Bundle b = getArguments();
        if (b != null) {
            transData = b.getParcelable(TRANS_DATA);
            //有的交易名称很长，放不下（已修正）
            if (transData.getTransType().getName() != 0) {
                setTipTitle(getString(transData.getTransType().getName()));
            }
            showTip(b.getString(TIP));
        }
        new OnlinePresenter(this, Repository.getInstance(), transData);
    }

    @Override
    public void onResume() {
        super.onResume();
        mPresenter.start();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        cancelDownTimer();
        mPresenter.destroy();
    }

    @Override
    public ActionStep getActionStep() {
        return ActionStep.ONLINE;
    }

    @Override
    public void setPresenter(OnlineContract.Presenter presenter) {
        mPresenter = presenter;
    }


    @Override
    public void showTip(String tip) {
        if (TextUtils.isEmpty(tip)) return;
        setTip(tip);
        if (mCountTime != 0){
            startDownTimer();
        }
    }

    @Override
    public void showOnlineQuit() {
        dismiss();
        if (mListener != null) {
            mListener.setActionResult(new ActionResult(OnlineDialogFragment.this, ActionResult.ERR_CANCEL, null));
        }
    }

    @Override
    public void showNetworkError() {
        dismiss();
        TextDialogFragment networkDialog = TextDialogFragment.newInstance();
        networkDialog.setDialogType(TextDialogFragment.DIALOG_TYPE_WRONG);
        networkDialog.setTitleText(getString(R.string.trans_fail));
        networkDialog.setContentText(getString(R.string.comm_network_exception), Gravity.CENTER);
        networkDialog.setPositionText(getString(R.string.confirm));
        networkDialog.setDialogListener(new TextDialogFragment.OnDialogListener() {
            @Override
            public void onCancel() {}

            @Override
            public void onConfirm() {
                if (mListener != null) {
                    mListener.setActionResult(new ActionResult(OnlineDialogFragment.this, ActionResult.ERR_CANCEL, null));
                }
            }
        });
        networkDialog.show(getFragmentManager(), null);
    }

    @Override
    public void showConnectError() {
        showNetworkError();
    }

    @Override
    public void showReceiveTimeout() {
        dismiss();
        TextDialogFragment networkDialog = TextDialogFragment.newInstance();
        networkDialog.setDialogType(TextDialogFragment.DIALOG_TYPE_WRONG);
        networkDialog.setTitleText(getString(R.string.trans_fail));
        networkDialog.setContentText(getString(R.string.comm_timeout), Gravity.CENTER);
        networkDialog.setPositionText(getString(R.string.confirm));
        networkDialog.setDialogListener(new TextDialogFragment.OnDialogListener() {
            @Override
            public void onCancel() {}

            @Override
            public void onConfirm() {
                dismiss();
                if (mListener != null) {
                    mListener.setActionResult(new ActionResult(OnlineDialogFragment.this, ActionResult.ERR_TIMEOUT, null));
                }
            }
        });
        networkDialog.show(getFragmentManager(), null);
    }

    @Override
    public void showOnlineError() {
        dismiss();
        TextDialogFragment networkDialog = TextDialogFragment.newInstance();
        networkDialog.setDialogType(TextDialogFragment.DIALOG_TYPE_WRONG);
        networkDialog.setTitleText(getString(R.string.trans_fail));
        networkDialog.setContentText(getString(R.string.comm_network_exception_init), Gravity.CENTER);
        networkDialog.setPositionText(getString(R.string.confirm));
        networkDialog.setDialogListener(new TextDialogFragment.OnDialogListener() {
            @Override
            public void onCancel() {}

            @Override
            public void onConfirm() {
                dismiss();
                if (mListener != null) {
                    mListener.setActionResult(new ActionResult(OnlineDialogFragment.this, ActionResult.ERR_FAIL, null));
                }
            }
        });
        networkDialog.show(getFragmentManager(), null);
    }

    @Override
    public void showSuccessful(MessageData messageData) {
        dismiss();
        if (mListener != null) {
            mListener.setActionResult(new ActionResult(this, ActionResult.SUCC, messageData));
        }
    }

    @Override
    public boolean isActive() {
        return isAdded();
    }

    @Override
    public void setCountDown(int timeOut) {
        this.mCountTime = timeOut;
        if (mCountTime != 0){
            startDownTimer();
        }
    }

    @Override
    public void showCheckLocationFail() {
        TextDialogFragment dialogFragment = TextDialogFragment.newInstance();
        dialogFragment.setDialogType(TextDialogFragment.DIALOG_TYPE_WARNING);
        dialogFragment.setTitleText(getString(R.string.kindly_tip));
        dialogFragment.setContentText(getString(R.string.gps_failed), Gravity.CENTER);
        dialogFragment.setPositionText(getString(R.string.confirm));
        dialogFragment.setDialogListener(new TextDialogFragment.OnDialogListener() {
            @Override
            public void onCancel() {

            }
            @Override
            public void onConfirm() {
                dismiss();
                if (mListener != null) {
                    mListener.setActionResult(new ActionResult(OnlineDialogFragment.this, ActionResult.ERR_GPS, null));
                }
            }
        });
        dialogFragment.show(getFragmentManager(), null);
    }

    /**
     * 开始倒计时
     */
    private void startDownTimer(){
        if (mDownTimer != null){
            mDownTimer.cancel();
            mDownTimer = null;
        }
        mDownTimer = new MyDownTimer((mCountTime + 1) * 1000);
        mDownTimer.start();
    }

    /**
     * 取消倒计时
     */
    private void cancelDownTimer(){
        if (mDownTimer != null) mDownTimer.cancel();
    }

    /**
     * 倒计时
     */
    class MyDownTimer extends CountDownTimer{

        private String tips;

        public MyDownTimer(long millisInFuture){
            this(millisInFuture, 1000);
            this.tips = getTip();
        }

        public MyDownTimer(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);
        }

        @Override
        public void onTick(long millisUntilFinished) {
            if (!isActive()) return;
            setTip(tips + "(" + StringUtils.leftPad(String.valueOf(millisUntilFinished/1000), 2, '0') + ")");
        }

        @Override
        public void onFinish() {
            if (!isActive()) return;
            setTip(tips + "(00)");
        }
    }

    @Override
    public void showError(String message) {
        SoundManager soundManager = new SoundManager();
        soundManager.play(SoundManager.Type.TRANS_FAIL);
        TextDialogFragment dialogFragment = TextDialogFragment.newInstance();
        dialogFragment.setDialogType(TextDialogFragment.DIALOG_TYPE_WRONG);
        dialogFragment.setTitleText(getString(R.string.tip));
        dialogFragment.setContentText(message, Gravity.CENTER);
        dialogFragment.setPositionText(getString(R.string.confirm));
        dialogFragment.setDownTimer(SysConstant.TIME_OUT_10, true);
        dialogFragment.setDialogListener(new TextDialogFragment.OnDialogListener() {
            @Override
            public void onCancel() {

            }

            @Override
            public void onConfirm() {
                dismiss();
                if (mListener != null) {
                    mListener.setActionResult(new ActionResult(OnlineDialogFragment.this, ActionResult.ERR_FAIL, null));
                }
            }
        });
        dialogFragment.show(getFragmentManager(), null);
    }

}
